package com.ocom.ugcapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.card.EntityCardInfo;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.human.EntityRoommateInfo;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.entity.master.EntityWechatPerInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.ugcapi.WxGzhLoginVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.company.GzhPerInfoVo;
import com.ocom.common.vo.human.UserInfoYkmVo;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.common.vo.ugcapi.GzhUserInfo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.ugcapi.client.CompanyClientService;
import com.ocom.ugcapi.client.HumanClientService;
import com.ocom.ugcapi.client.PayConfigClientService;
import com.ocom.ugcapi.config.RsaConfig;
import com.ocom.ugcapi.service.LoginService;
import com.ocom.ugcapi.util.RSAHelper;
import com.ocom.ugcapi.vo.OauthLoginVo;
import com.ocom.ugcapi.vo.SmsLoginVo;
import com.ocom.ugcapi.vo.UgcLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

//    @Value("${gzh.appid}")
//    String appid;
//
//    @Value("${gzh.secret}")
//    String secret;

    @Autowired
    private HumanClientService humanClientService;


    @Autowired
    private PayConfigClientService payConfigClientService;



    @Autowired
    CompanyClientService companyClientService;

    @Resource
    private RedisUtil redisUtil;

    // 获取openId (/getOpenId)
    @Override
    public Result GetOpenId(String code,String state) {

        GzhUserInfo user = null;
        Gson gson=new Gson();
        try {

            Object userObject = redisUtil.get("gzhMd5:"+state);
            if(userObject == null){
                return ResultUtil.error(ResultEnum.Err_3041);
            }
            //绑定后删除
            redisUtil.del("gzhMd5:"+state);
            user = gson.fromJson(userObject.toString(), GzhUserInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.Err_3041);
        }


        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + user.getAppId() + "&secret=" + user.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";

        Map map = JSON.parseObject(HttpRequest.sendGet(url), Map.class);
        //{{errcode=40125, errmsg=invalid appsecret, rid: 688d9172-28ed9973-0800ffc6}}
        //{{access_token=94_jCfWyTn2rLyfEW3KnkOOPZSVZV0S4CcIof2Y9FOypOIOiGHjDpi_ZzVyEzR9Csh409_WnQIkN_RJcUd9Ry-GGpCuG5n8U-LC76Y3133B_is, refresh_token=94_0-mrATcIofvY9gJnHxrORR_uszq5OzOwcugEBuJH5ojc3KscuZUCUPJa3lEx_cKzBfWnG4Ra5UdH6BpHFWlZBkVM8cZoJJ7GYbPXnjBD3L8, openid=oCKkm6QMIuq22_Y2uXx91tAUzS4E, scope=snsapi_base, expires_in=7200}}
        log.info("登录 微信返回信息 uw25IRQivqy9 = {{}}", map);

        if (map.containsKey("errcode")) {
            return ResultUtil.info(500, map.get("errmsg").toString());
        }

        String openId = map.get("openid").toString();
        user.setOpenId(openId);

        //返回数据
        Map<String, Object> map1 = new HashMap<>();

        //是否已签约
        Integer type =0;
        //是否有消费账户
        Boolean flag =true;
        String token = null;

        if (StringUtils.isNotBlank(state) && state.startsWith("XAK")) {

            Result result = humanClientService.GetWxPerson(user.getAppId(), openId,user.getComId());

            log.info("根据openid 获取人员 【{}】【{}】【{}】【{}】",user,state,openId,result);
            if (200 != result.getCode()){
                return result;
            }
            EntityWechatPerInfo wechatPerInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatPerInfo.class);
            if (null == wechatPerInfo) {
                return ResultUtil.error(ResultEnum.Err_3041);
            }
            user.setPId(wechatPerInfo.getPId());

            Object o = redisUtil.get("gzhToken:" + user.getComId() + ":" + user.getPId());
            if (null != o) {
                user = JSON.parseObject(JSON.parse(JSON.toJSONString(o)).toString(), GzhUserInfo.class);
                token = RSAHelper.encipher(gson.toJson(user),RsaConfig.publicKey,200);
                log.info("登录Token1:" +token);
                // PasswordCorrect需要设置true
            }
            user.setPasswordCorrect(true);
            // else {
//                return ResultUtil.error(ResultEnum.Err_2042);
//            }

        }  // else {
        if(CommonUtil.isNull(token)){
            /**
             * 判断用户支付信息
             */
            //获取用户信息
            Result result22 = humanClientService.getXfUserInfo(user.getComId(),user.getPId());
            log.info("登录- 支付人员信息 【{}】 ", result22);
            if(result22.getCode()!=200){
                log.info("登录- 支付人员信息获取失败 【{}】【{}】 ",user, result22);
                flag = false;
                return result22;
            }
            XfUserInfoVo xfUserInfoVo=gson.fromJson(gson.toJson(result22.getData()),XfUserInfoVo.class);

            if(xfUserInfoVo.getSignType()!=0 && !CommonUtil.isNull(xfUserInfoVo.getSignNo())){
                type = xfUserInfoVo.getSignType();
                user.setSignType(type);
            }

            try {
//            token = encryptOpenId(user.getAppId()+"##"+user.getOpenId());
                token = RSAHelper.encipher(gson.toJson(user),RsaConfig.publicKey,200);
                log.info("登录Token:" +token);

//                redisUtil.set("gzhToken:"+user.getComId()+":"+user.getPId(), gson.toJson(user),31536000l);

                if (StringUtils.isNotBlank(state) && state.startsWith("XAK")) {
                    redisUtil.set("gzhToken:"+user.getComId()+":"+user.getPId(), gson.toJson(user),86400l*7l);
                }else{
                    redisUtil.set("gzhToken:"+user.getComId()+":"+user.getPId(), gson.toJson(user),86400l*30l);
                }

            }catch (Exception e){
                log.info("登录生成token异常 【{}】", e);
                return ResultUtil.error(ResultEnum.Err_4003);
            }

            EntityWechatPerInfo entityWechatPerInfo = new EntityWechatPerInfo();
            entityWechatPerInfo.setComId(user.getComId());
            entityWechatPerInfo.setPId(user.getPId());
            entityWechatPerInfo.setAppid(user.getAppId());
            entityWechatPerInfo.setOpenid(openId);
            Result result = humanClientService.addWxper(entityWechatPerInfo);
            log.info("返回: 【{}】【{}】",user,result);
        }

//        map1.put("openId", openId);
        map1.put("token", token);
        map1.put("type", type);
        map1.put("flag", flag);
        map1.put("passwordCorrect", user.getPasswordCorrect());
        return ResultUtil.success(map1);
    }

    @Override
    public Result stateParam(Long comId) {
        Gson gson=new Gson();
        Map<String, Object> map = new HashMap<>();

        String appId ="wx72e8e32913ece43a";
        String appSecret ="c2a038154a764f7712f8acf5026b9e1b";

        GzhUserInfo userInfo=new GzhUserInfo();

        Result result1 = payConfigClientService.getWxInfo(comId,0l);
        if(result1.getCode()==200){
            JSONObject jsonObject=JSON.parseObject(JSON.toJSONString( result1.getData()));
            appId =jsonObject.getString("appid");
            appSecret =jsonObject.getString("appsecret");
            userInfo.setFlag(true);
        }
        String state = "";
        try {

            userInfo.setComId(comId);
//            userInfo.setPId();
            userInfo.setAppId(appId);
            userInfo.setAppSecret(appSecret);
//            userInfo.setPPhone();
//            userInfo.setPasswordCorrect();
            String user = gson.toJson(userInfo);
            String generateNumber = RandomUtil.getRandomString(32);

            state = "xak" + MD5.MD5Encode(generateNumber,"utf8");
            state = state.toUpperCase(Locale.ROOT);
            redisUtil.set("gzhMd5:"+  state, user,120l);

            log.info("生成user", user);

            map.put("appId", appId);
            map.put("state", state);
        } catch (Exception e) {
            e.printStackTrace();
            ResultUtil.error(ResultEnum.Err_900);
        }
        return ResultUtil.success(map);
    }

    @Override
    public Result Login(UgcLoginVo ugcLoginVo) {

        log.info("公众号登录参数 mFWM5ObE 【{}】 【{}】",ugcLoginVo.getComId(),ugcLoginVo);

        //单点登录判断
        if(ugcLoginVo.getFrom()!=null && !ugcLoginVo.getFrom().equals("gzh") && !ugcLoginVo.getFrom().equals("h5")){
            if(CommonUtil.isNull(ugcLoginVo.getState())){
                ResultUtil.error(ResultEnum.Err_2047);
            }
        }


        Map<String, Object> map = new HashMap<>();

        if(CommonUtil.isNull(ugcLoginVo.getCardNo())){
            if(CommonUtil.isNull(ugcLoginVo.getUsername()) || CommonUtil.isNull(ugcLoginVo.getPhone()) ){
                return ResultUtil.error(ResultEnum.Err_3061);
            }
        }else {
            Result cardInfoByCardNo = payConfigClientService.getCardInfoByCardNo(ugcLoginVo.getComId(), ugcLoginVo.getCardNo());
            if (200 != cardInfoByCardNo.getCode() || null == cardInfoByCardNo.getData()) {
                return ResultUtil.error(ResultEnum.Err_816);
            }
            EntityCardInfo entityCardInfo = JSON.parseObject(JSON.toJSONString(cardInfoByCardNo.getData()), EntityCardInfo.class);
            map.put("pId",entityCardInfo.getPId());
        }

        Gson gson=new Gson();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),ugcLoginVo.getComId());

        map.put("pCode",ugcLoginVo.getPhone());
        map.put(mapKey.getKey_page(),1);
        map.put(mapKey.getKey_size(),1);
        Result result = humanClientService.PersonnelGetPersonInfo(map);
        if (result.getCode()!=200){
            return ResultUtil.error(result.getCode());
        }
        String list = JSON.parseObject(JSON.toJSONString(result.getData())).get("list").toString();
        List<UserInfoYkmVo> userInfoYkmVos = JSON.parseArray(list, UserInfoYkmVo.class);
        Map<String, Object> map1 = new HashMap<>();
        if (userInfoYkmVos.size()>0){
            UserInfoYkmVo userInfoYkmVo =  userInfoYkmVos.get(0) ;
            if (CommonUtil.isNull(ugcLoginVo.getCardNo())) {
                if(!ugcLoginVo.getUsername().equals(userInfoYkmVo.getPName())){
                    return ResultUtil.error(ResultEnum.Err_2036);
                }
            }

            Boolean passwordCorrect = true;

            if (userInfoYkmVo.getPPwd() != null ){
                if (!userInfoYkmVo.getPPwd().equals(ugcLoginVo.getPassword())){
                    if(ugcLoginVo.getPassword().equals("123456") && CommonUtil.isNull(userInfoYkmVo.getPPwd())){
                        //正常往下走
                        passwordCorrect=false;
                    }else{
                        return ResultUtil.error(ResultEnum.Err_311);
                    }
                }
            }
            if(ugcLoginVo.getPassword().equals("123456")){
                passwordCorrect=false;
            }

            Result<List<EntityCompanyConfig>> result3 = companyClientService.getCompanyConfig(ugcLoginVo.getComId(),"allowWeakPasswords");
            log.info("读取到配置 sz1W9SL1 【{}】【{}】",ugcLoginVo,result3);
            if(result3.getCode()!=200 || result3.getData() ==null || !"true".equals(result3.getData().get(0).getConfig()) ){
                List<String> errors = PasswordValidator.validatePassword(ugcLoginVo.getPassword());
                if (!errors.isEmpty()) {
                    passwordCorrect=false;
                }
                log.info("读取到配置 sz1W9SL1 【{}】【{}】",ugcLoginVo,ugcLoginVo.getPassword(),passwordCorrect);
            }
//            Collections.addAll(checkComId, 75l, 77l, 89l, 106l, 113l, 123l, 126l, 127l, 130l, 133l,
//                    526l, 584l, 619l, 622l, 626l, 633l, 656l, 670l, 671l, 678l, 680l, 706l);
//            String appId ="wxce325449f6daff0c";
//            String appSecret ="cfb1d8197bf201c6f3bad4b8cbf31e97";
//            String appId ="wx4f9f6bd221934c14";
//            String appSecret ="4b73282e981e116f0a80bace902ae17c";
            String appId ="wx72e8e32913ece43a";
            String appSecret ="c2a038154a764f7712f8acf5026b9e1b";
            //TODO 获取appid 和 appSecret

            GzhUserInfo userInfo=new GzhUserInfo();

            Result result1 = payConfigClientService.getWxInfo(ugcLoginVo.getComId(),0l);
            if(result1.getCode()==200){
//                    return ResultUtil.error(ResultEnum.Err_3045);
                JSONObject jsonObject=JSON.parseObject(JSON.toJSONString( result1.getData()));
                appId =jsonObject.getString("appid");
                appSecret =jsonObject.getString("appsecret");
                userInfo.setFlag(true);
            }

            String state = "";
            try {

                userInfo.setComId(userInfoYkmVo.getComId());
                userInfo.setPId(userInfoYkmVo.getPId());
                userInfo.setAppId(appId);
                userInfo.setAppSecret(appSecret);
                userInfo.setPPhone(userInfoYkmVo.getPPhone());
                userInfo.setPasswordCorrect(passwordCorrect);

                String user = gson.toJson(userInfo);
                state = MD5.MD5Encode(userInfoYkmVo.getComId()+"##"+userInfoYkmVo.getPId(),"utf8");
                state = state.toUpperCase(Locale.ROOT);
                redisUtil.set("gzhMd5:"+state, user,120l);

                log.info("生成Token", user);
            } catch (Exception e) {
                e.printStackTrace();
            }
            map1.put("state", state);
            map1.put("appId", appId);
            map1.put("passwordCorrect", passwordCorrect);

            //直接登录 不调公众号
            if(ugcLoginVo.getFrom()!=null && ugcLoginVo.getFrom().equals("h5")){
                String token = RSAHelper.encipher(gson.toJson(userInfo),RsaConfig.publicKey,200);
                redisUtil.set("gzhToken:"+userInfoYkmVo.getComId()+":"+userInfoYkmVo.getPId(), gson.toJson(userInfo),86400l*30l);
                map1.put("token", token);
            }

            //单点登录处理
            if(ugcLoginVo.getFrom()!=null && !ugcLoginVo.getFrom().equals("gzh") && !ugcLoginVo.getFrom().equals("h5")){

                OauthLoginVo oauthLoginVo  = (OauthLoginVo)redisUtil.get("gzhMd5Auth:"+  ugcLoginVo.getState());
                String token = RSAHelper.encipher(gson.toJson(userInfo),RsaConfig.publicKey,200);
                redisUtil.set("gzhToken:"+userInfoYkmVo.getComId()+":"+userInfoYkmVo.getPId(), gson.toJson(userInfo),86400l*30l);
                map1.put("token", token);
                EntityWechatPerInfo entityWechatPerInfo = new EntityWechatPerInfo();
                entityWechatPerInfo.setComId(userInfoYkmVo.getComId());
                entityWechatPerInfo.setPId(userInfoYkmVo.getPId());
                entityWechatPerInfo.setAppid(oauthLoginVo.getAppid());
                entityWechatPerInfo.setOpenid(oauthLoginVo.getUserId());
                humanClientService.addWxper(entityWechatPerInfo);
                log.info("单点登录绑定人员: 【{}】【{}】",ugcLoginVo,entityWechatPerInfo);
            }


        }else {
            return ResultUtil.error(ResultEnum.Err_816);
        }
        return ResultUtil.success(map1);
    }

    @Override
    public Result Login(SmsLoginVo smsLoginVo) {
        if(CommonUtil.isNull(smsLoginVo.getCode())
                || CommonUtil.isNull(smsLoginVo.getPhone())
                || smsLoginVo.getComId()==null
                || smsLoginVo.getComId()==0l){
            return ResultUtil.error(ResultEnum.Err_3065);
        }

        log.info("公众号登录参数 8Ttmi9Zr 【{}】 【{}】",smsLoginVo.getComId(),smsLoginVo);


        //step 1 验证手机号
        Object code =  redisUtil.get("gzh:signCode:"+smsLoginVo.getComId()+":"+smsLoginVo.getPhone()+":" +smsLoginVo.getCode());
        if(code == null){
            return ResultUtil.error(ResultEnum.Err_2002);
        }

        Map<String, Object> map = new HashMap<>();
        Gson gson=new Gson();
        map.put("comId",smsLoginVo.getComId());
        map.put("pPhone",smsLoginVo.getPhone());
        map.put("page",1);
        map.put("size",1);
        Result result = humanClientService.PersonnelGetPersonInfo(map);
        if (result.getCode()!=200){
            return ResultUtil.error(result.getCode());
        }
        String list = JSON.parseObject(JSON.toJSONString(result.getData())).get("list").toString();
        List<UserInfoYkmVo> userInfoYkmVos = JSON.parseArray(list, UserInfoYkmVo.class);
        Map<String, Object> map1 = new HashMap<>();
        if (userInfoYkmVos.size()>0){
            UserInfoYkmVo userInfoYkmVo =  userInfoYkmVos.get(0) ;

            Boolean passwordCorrect = true;

            if(userInfoYkmVo.getPPwd().equals("123456")){
                passwordCorrect=false;
            }
//            String appId ="wx4f9f6bd221934c14";
//            String appSecret ="4b73282e981e116f0a80bace902ae17c";
            String appId ="wx72e8e32913ece43a";
            String appSecret ="c2a038154a764f7712f8acf5026b9e1b";
            //TODO 获取appid 和 appSecret

            GzhUserInfo userInfo=new GzhUserInfo();

            Result result1 = payConfigClientService.getWxInfo(smsLoginVo.getComId(),0l);
            if(result1.getCode()==200){
//                    return ResultUtil.error(ResultEnum.Err_3045);
                JSONObject jsonObject=JSON.parseObject(JSON.toJSONString( result1.getData()));
                appId =jsonObject.getString("appid");
                appSecret =jsonObject.getString("appsecret");
                userInfo.setFlag(true);
            }
            String state = "";
            try {

                userInfo.setComId(userInfoYkmVo.getComId());
                userInfo.setPId(userInfoYkmVo.getPId());
                userInfo.setAppId(appId);
                userInfo.setAppSecret(appSecret);
                userInfo.setPPhone(userInfoYkmVo.getPPhone());
                userInfo.setPasswordCorrect(passwordCorrect);
                String user = gson.toJson(userInfo);
                state = MD5.MD5Encode(userInfoYkmVo.getComId()+"##"+userInfoYkmVo.getPId(),"utf8");
                state = state.toUpperCase(Locale.ROOT);
                redisUtil.set("gzhMd5:"+state, user,120l);

                log.info("生成Token", user);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //更新姓名和同住人信息
            try {
                if(!CommonUtil.isNull(smsLoginVo.getFName())){
                    EntityRoommateInfo entityRoommateInfo=new EntityRoommateInfo();
                    entityRoommateInfo.setComId(userInfoYkmVo.getComId());
                    entityRoommateInfo.setPId(userInfoYkmVo.getPId());
                    entityRoommateInfo.setPhone(userInfoYkmVo.getPPhone());
                    entityRoommateInfo.setType("监护人");
                    entityRoommateInfo.setName(smsLoginVo.getFName());
                    humanClientService.AddRoommate(entityRoommateInfo);
                }
                if(!CommonUtil.isNull(smsLoginVo.getPName())){
                    PersonVo personVo=new PersonVo();
                    personVo.setComId(userInfoYkmVo.getComId());
                    personVo.setPId(userInfoYkmVo.getPId());
                    personVo.setPName(smsLoginVo.getPName());
                    humanClientService.UpdatePerson(personVo);
                }
            } catch (Exception e) {
                log.info("更新姓名出异常 【{}】",e);
                e.printStackTrace();
            }
            map1.put("state", state);
            map1.put("appId", appId);
            map1.put("passwordCorrect", passwordCorrect);

        }else {
            return ResultUtil.error(ResultEnum.Err_816);
        }
        return ResultUtil.success(map1);
    }

    @Override
    public Result Logout(String token) {
        // 解析token
        GzhUserInfo user = null;
        try {
            Gson gson=new Gson();
            String userStr  = RSAHelper.decipher(token,RsaConfig.privateKey);
            user = gson.fromJson(userStr,GzhUserInfo.class);
        } catch (Exception e) {
            log.info("Token解析异常 【{}】", e);
            return ResultUtil.error(ResultEnum.Err_3042);
        }
        log.info("token解析数据{{}}",user);
//        humanClientService.DelWxPerson(user.getAppId(),user.getOpenId());
        redisUtil.del("gzhToken:"+user.getComId()+":"+user.getPId());
        return ResultUtil.success();
    }


    @Override
    public Result WxGzhLogin(WxGzhLoginVo wxGzhLoginVo) {
        //获取公众号信息
        Result result = companyClientService.getAppInfoByName(wxGzhLoginVo.getAppName())     ;
        if(result.getCode()!=200){
            return result;
        }


        Boolean existPerson =false;
        GzhUserInfo user = new GzhUserInfo();

        if(wxGzhLoginVo.getAuthCode().equals("ocom")){

            user.setAppId("ocom");
            user.setAppSecret("123456");
            user.setFlag(true);
            user.setPasswordCorrect(true);
            //重要
            user.setComId(0l);

            SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 5, 2);

            user.setPId(snowflakeIdWorker.nextId());
            user.setAppName(wxGzhLoginVo.getAppName());

            user.setOpenId(RandomUtil.generateNumber(10));

        }else{
            EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + entityWechatAppInfo.getAppid() + "&secret=" + entityWechatAppInfo.getAppsecret() + "&code=" + wxGzhLoginVo.getAuthCode() + "&grant_type=authorization_code";

            Map map = JSON.parseObject(HttpRequest.sendGet(url), Map.class);

            if(map.containsKey("errcode")){
                return ResultUtil.info(400,map.get("errmsg").toString());
            }

            log.info("登录 微信返回信息 68= {{}}", map);

            String openId = map.get("openid").toString();


            user.setAppId(entityWechatAppInfo.getAppid());
            user.setAppSecret(entityWechatAppInfo.getAppsecret());
            user.setFlag(true);
            user.setPasswordCorrect(true);

            //重要
            user.setComId(0l);

            SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 5, 2);

            user.setPId(snowflakeIdWorker.nextId());
            user.setAppName(wxGzhLoginVo.getAppName());

            user.setOpenId(openId);

            //查找人员
            Result result1 = companyClientService.getPersonListByOpenid(openId,entityWechatAppInfo.getAppid());

            if(result1.getCode()==200){
                List<GzhPerInfoVo> perInfoVos = JSON.parseArray(JSON.toJSONString(result1.getData()), GzhPerInfoVo.class);
                user.setPId(perInfoVos.get(0).getPId());
                user.setComId(perInfoVos.get(0).getComId());
                existPerson = true;
            }
        }



        String token;
        try {
            Gson gson=new Gson();

            token = RSAHelper.encipher(gson.toJson(user),RsaConfig.publicKey,200);
            log.info("登录Token:" +token);

            redisUtil.set("gzhToken:"+user.getComId()+":"+user.getPId(), gson.toJson(user),3600l);
        }catch (Exception e){
            log.info("登录生成token异常 【{}】", e);
            return ResultUtil.error(ResultEnum.Err_4003);
        }

        //返回数据
        Map<String, Object> map1 = new HashMap<>();
        map1.put("token", token);
        map1.put("type", 0);
        map1.put("flag", true);
        map1.put("passwordCorrect", true);
        map1.put("existPerson", existPerson);
        return ResultUtil.success(map1);
    }





    @Override
    public Result lanzhouLogin(Long comId,String appId,String userId,String from) {

        Result<EntityWechatPerInfo> result = humanClientService.GetWxPerson(appId, userId ,comId);

        Map<String, Object> map = new HashMap<>();

        if(result.getCode()==200 && result.getData()!=null){
            GzhUserInfo user = new GzhUserInfo();
            user.setComId(result.getData().getComId());
            user.setPId(result.getData().getPId());
            user.setAppId(appId);
            user.setAppSecret("");
            user.setAppName("农行e");
            user.setOpenId(userId);
            user.setPasswordCorrect(true);

            Gson gson=new Gson();
            String token = RSAHelper.encipher(gson.toJson(user),RsaConfig.publicKey,200);
            log.info("登录Token:" +token);

            redisUtil.set("gzhToken:"+user.getComId()+":"+user.getPId(), gson.toJson(user),86400l*7l);

            map.put("token", token);
            map.put("type", 0);
            map.put("flag", true);
            map.put("passwordCorrect", true);
            map.put("existPerson", true);
            return ResultUtil.success(map);
        }

        String state = "";
        try {
            String generateNumber = RandomUtil.getRandomString(32);
            state = from + MD5.MD5Encode(generateNumber,"utf8");
            state = state.toUpperCase(Locale.ROOT);

            OauthLoginVo oauthLoginVo =new OauthLoginVo();
            oauthLoginVo.setAppid(appId);
            oauthLoginVo.setUserId(userId);
            oauthLoginVo.setComId(comId);

            redisUtil.set("gzhMd5Auth:"+  state, oauthLoginVo ,180l);
            map.put("state", state);
            map.put("from", from);
            map.put("comId", comId);
        } catch (Exception e) {
            e.printStackTrace();
            ResultUtil.error(ResultEnum.Err_900);
        }
        return ResultUtil.success(map);

    }






    public static void main(String[] args){
        String token = RSAHelper.encipher("",RsaConfig.publicKey,200);
        System.out.println(token);


        String ouyuy = RSAHelper.decipher(token,RsaConfig.privateKey);
        System.out.println(ouyuy);
    }

}
